var VS_SHADER_RESOURCE = 
    'attribute vec4 a_Position;\n'+
    'void main() { \n'+
    ' gl_Position = a_Position;\n'+
    ' gl_PointSize = 10.0;\n'+
    '}\n';

var FS_SHADER_RESOURCE =
    'precision mediump float;\n' +
    'uniform vec4 u_FragColor;\n'+
    'void main() {\n'+
    ' gl_FragColor = u_FragColor;\n'+
    '}\n';

var positions = [];
var colors = [];
function main(){

    let canvas = document.getElementById('canvas_id');
    let gl = getWebGLContext(canvas);
    if(! gl){
        console.error("no find gl");
        return;
    }
    if(! initShaders(gl, VS_SHADER_RESOURCE, FS_SHADER_RESOURCE)){
        console.error("init shader fail");
        return;
    }

    let a_Position = gl.getAttribLocation(gl.program, 'a_Position');
    let u_FragColor = gl.getUniformLocation(gl.program, 'u_FragColor');
    gl.clearColor(0.0,0.0,0.0,1.0);
    gl.clear(gl.COLOR_BUFFER_BIT);
    canvas.onmousemove = function(ev){
        click(ev,gl,canvas, a_Position,u_FragColor);
    }
    
}

function click(ev, gl, canvas, a_Position,u_FragColor)
{
    let x = ev.clientX;
    let y = ev.clientY;
    let rect = ev.target.getBoundingClientRect();
    x = ((x - rect.left) - canvas.height /2)/(canvas.height/2);
    y = ((y - rect.top) - canvas.width /2)/(-canvas.width/2);
    positions.push(x,y);
    console.log("位置信息更新: x->"+ x+ "  y->"+y);
    if(y > 0){
        colors.push([0.0,1.0,0.0,1.0]);
    }else{
        
        colors.push([0.0,0.0,1.0,1.0]);
    }
    gl.clearColor(0.0,0.0,0.0,1.0);
    gl.clear(gl.COLOR_BUFFER_BIT);
    for (let index = 0; index < positions.length; index+=2) {
        const p1 = positions[index];
        const color = colors[index/2];
        // gl.clear(gl.COLOR_BUFFER_BIT)
        gl.vertexAttrib2f(a_Position, p1, positions[index+1]);
        gl.uniform4f(u_FragColor, color[0], color[1], color[2], color[3]);
        gl.drawArrays(gl.POINT, 0, 1);
    }

}
function click2(ev, gl, canvas, a_Position,u_FragColor) // 并不会缓存绘制信息
{
    let x = ev.clientX;
    let y = ev.clientY;
    let color;
    let rect = ev.target.getBoundingClientRect();
    x = ((x - rect.left) - canvas.height /2)/(canvas.height/2);
    y = ((y - rect.top) - canvas.width /2)/(-canvas.width/2);
    if(y > 0){
        color = ([0.0,1.0,0.0,1.0]);
    }else{
        
        color = ([0.0,0.0,1.0,1.0]);
    }
    

    gl.vertexAttrib2f(a_Position, x,y);
    gl.uniform4f(u_FragColor, color[0], color[1], color[2], color[3]);
    gl.drawArrays(gl.POINT, 0, 1);

}